<template>
  <div
    v-loading="loading"
    element-loading-text="加载中..."
    style="display: flex; flex-direction: column; height: 100%"
  >
    <div class="top">
      <ul>
        <li>
          <p>本月入库</p>
          <span>{{ Number(InWidthOutStoreQty?.inStoreQty || 0).toLocaleString() }}</span>
        </li>
        <li class="border-left">
          <p>本月出库</p>
          <span>{{ Number(InWidthOutStoreQty?.outStoreQty || 0).toLocaleString() }}</span>
        </li>
      </ul>
    </div>
    <div class="app-container" style="display: flex; flex-direction: column; height: 100%">
      <div
        class="app-container-inner"
        style="display: flex; flex-direction: column; flex: 1; height: 100%"
      >
        <div class="header">
          <div class="create-sto" style="display: flex; gap: 5px">
            <HPlainButton @click="showAdd"> 添加仓库 </HPlainButton>
            <el-dropdown trigger="click">
              <HButton :disabled="ids.length == 0">
                批量操作
                <el-icon class="el-icon--right">
                  <arrow-down />
                </el-icon>
              </HButton>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="changeAll(1, '要启用仓库')">
                    <el-icon>
                      <CircleCheck />
                    </el-icon>
                    批量启用
                  </el-dropdown-item>
                  <el-dropdown-item @click="changeAll(2, '要禁用仓库')">
                    <el-icon>
                      <Warning />
                    </el-icon>
                    批量禁用
                  </el-dropdown-item>
                  <el-dropdown-item @click="changeAll(4, `修改为'允许负库存'`)">
                    <el-icon>
                      <FolderChecked />
                    </el-icon>
                    允许负库存
                  </el-dropdown-item>
                  <el-dropdown-item @click="changeAll(5, `修改为'不允许负库存'`)">
                    <el-icon>
                      <FolderRemove />
                    </el-icon>
                    不允许负库存
                  </el-dropdown-item>
                  <el-dropdown-item @click="changeAll(3, '要删除仓库')">
                    <el-icon>
                      <Delete />
                    </el-icon>
                    批量删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
          <div class="search">
            <el-select
              v-model="storeListSearch.outStoreExample"
              class="mr5 w100"
              @keyup.enter="getListStoreRows"
              clearable
              placeholder="仓库类型"
            >
              <el-option label="内部仓库" :value="0" />
              <el-option label="服务商-外部仓库" :value="1" />
              <el-option label="工程师-外部仓库" :value="2" />
            </el-select>
            <el-input
              v-model="storeListSearch.storeSearch"
              class="mr5 w100"
              @keyup.enter="getListStoreRows"
              @clear="getListStoreRows"
              clearable
              placeholder="仓库名称/仓库编码"
            />
            <el-input
              v-model="storeListSearch.userSearch"
              class="mr5 w100"
              @keyup.enter="getListStoreRows"
              @clear="getListStoreRows"
              clearable
              placeholder="仓管/手机号"
            />
            <div class="filter">
              <HButton type="primary" @click="getListStoreRows">
                <el-icon>
                  <Search />
                </el-icon>
                搜索
              </HButton>
              <HButton class="reset_btn" @click="clearVlaue">
                <el-icon>
                  <RefreshRight />
                </el-icon>
                重置
              </HButton>
            </div>
          </div>
        </div>
        <!-- 列表 -->
        <div class="table" style="flex: 1; position: relative">
          <el-table
            border
            stripe
            resizable
            :data="tableDataList"
            height="100%"
            style="position: absolute"
            @selection-change="handleChange"
            @row-dblclick="goDetailPage"
          >
            <template #empty>
              <el-empty description="暂无数据" :image-size="140" />
            </template>
            <el-table-column type="selection" width="40" fixed />

            <!-- 序号 -->
            <el-table-column type="index" label="序号" width="50" fixed />

            <!-- 创库编码 -->
            <el-table-column show-overflow-tooltip prop="storeNo" label="仓库编码" width="120" />

            <!-- 仓库名称 -->
            <el-table-column show-overflow-tooltip prop="name" label="仓库名称" width="130">
              <template v-slot="item">
                <HLink @click="goDetailPage(item.row)">{{ item.row.name }}</HLink>
              </template>
            </el-table-column>

            <!-- 仓库类型 -->
            <el-table-column show-overflow-tooltip label="仓库类型" width="124">
              <template v-slot="item">
                <span>
                  {{
                    item.row.outStore
                      ? item.row.outStoreType == 1
                        ? '服务商 - 外部仓库'
                        : '工程师 - 外部仓库'
                      : '内部仓库'
                  }}
                </span>
              </template>
            </el-table-column>

            <!-- 允许负库存 -->
            <el-table-column label="允许负库存" width="86" align="center">
              <template #default="scope">
                <el-checkbox
                  disabled
                  v-if="scope.row.canNegativeStock"
                  :checked="scope.row.canNegativeStock"
                  size="large"
                />
              </template>
            </el-table-column>

            <!-- 启用仓库 -->
            <el-table-column label="启用仓位" width="74" align="center">
              <template #default="scope">
                <el-checkbox
                  disabled
                  v-if="scope.row.enableStorePosition"
                  :checked="scope.row.enableStorePosition"
                  size="large"
                />
              </template>
            </el-table-column>

            <!-- 仓管 -->
            <el-table-column show-overflow-tooltip prop="userName" label="仓管" width="100" />

            <!-- 电话 -->
            <el-table-column show-overflow-tooltip prop="userPhone" label="电话" width="104" />

            <!-- 仓库地址 -->
            <el-table-column show-overflow-tooltip label="仓库地址" min-width="240">
              <template v-slot="item">
                {{ item.row.province }}&nbsp;{{ item.row.city }}&nbsp;{{ item.row.area }}&nbsp;{{
                  item.row.town
                }}&nbsp;{{ item.row.address }}
              </template>
            </el-table-column>

            <!-- 状态 -->
            <el-table-column show-overflow-tooltip prop="status" label="状态" width="70">
              <template #default="scope">
                <HStatus type="info" v-if="scope.row.status">禁用</HStatus>
                <HStatus v-else>启用</HStatus>
              </template>
            </el-table-column>

            <!-- 创建时间 -->
            <el-table-column show-overflow-tooltip prop="createTime" label="创建时间" width="128" />

            <!-- 更新时间 -->
            <el-table-column show-overflow-tooltip prop="updateTime" label="更新时间" width="128" />

            <!-- 操作 -->
            <el-table-column fixed="right" label="操作" width="60">
              <template #default="scope">
                <HLink @click="getDetailStoreItem(scope.row.id)">编辑</HLink>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="footer">
          <Pagination
            ref="pagination"
            :list_total="total"
            @size-change="getListStoreRows"
            @current-change="getListStoreRows"
          />
        </div>

        <!-- 添加仓库弹窗 -->
        <HModal v-model="addDialog" :title="storeForm.id ? '编辑仓库' : '添加仓库'" :width="500">
          <div class="cards">
            <el-form
              ref="ruleFormRef"
              :model="storeForm"
              label-position="right"
              :rules="rulesStore"
              class="modal_form_content"
              label-width="90"
              @validate="handleFormValidate"
            >
              <el-form-item
                prop="outStoreExample"
                :class="{
                  form_select_item: true,
                  error_form_item: !formValidateResult['outStoreExample'],
                }"
              >
                <template #label>
                  <span>
                    仓库类型
                    <el-tooltip content="创建后不可更改" placement="top">
                      <el-icon>
                        <QuestionFilled />
                      </el-icon>
                    </el-tooltip>
                  </span>
                </template>
                <el-select
                  v-model="storeForm.outStoreExample"
                  :disabled="storeForm.id != null"
                  clearable
                  class="select_item"
                >
                  <el-option label="内部仓库" :value="0" />
                  <el-option label="服务商-外部仓库" :value="1" />
                  <el-option label="工程师-外部仓库" :value="2" />
                </el-select>
              </el-form-item>

              <el-form-item
                prop="relationId"
                :label="storeForm.outStoreExample == 1 ? '关联服务商' : '关联工程师'"
                v-if="storeForm.outStoreExample != 0"
                :class="{
                  form_select_item: true,
                  error_form_item: !formValidateResult['relationId'],
                }"
              >
                <el-select
                  v-model="storeForm.relationId"
                  placeholder="请选择"
                  clearable
                  @change="onRelationChange"
                  :disabled="storeForm.id != null"
                  filterable
                  reserve-keyword
                  :filter-method="onRelationREmoetMethod"
                  class="select_item"
                >
                  <el-option
                    v-for="item in outStoreRelation"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item
                label="仓库名称"
                prop="name"
                :class="{
                  form_input_item: true,
                  error_form_item: !formValidateResult['name'],
                }"
              >
                <el-input v-model="storeForm.name" clearable placeholder="仓库名称" />
              </el-form-item>
              <el-form-item
                label="仓库地址"
                prop="province"
                :class="{
                  form_select_item: true,
                  error_form_item: !formValidateResult['province'],
                }"
              >
                <SingleAddress ref="addrsDom" :address="addrs" @value-change="addressValChange" />
              </el-form-item>
              <el-form-item
                label="详细地址"
                prop="address"
                :class="{
                  form_input_item: true,
                  error_form_item: !formValidateResult['address'],
                }"
              >
                <el-input
                  v-model="storeForm.address"
                  clearable
                  class="detail"
                  placeholder="请输入详细地址"
                  maxlength="200"
                />
              </el-form-item>
              <el-form-item
                label="仓管"
                prop="userName"
                :class="{
                  form_input_item: true,
                  error_form_item: !formValidateResult['userName'],
                }"
              >
                <el-input v-model="storeForm.userName" clearable placeholder="仓管名称" />
              </el-form-item>
              <el-form-item
                label="电话"
                prop="userPhone"
                :class="{
                  form_input_item: true,
                  error_form_item: !formValidateResult['userPhone'],
                }"
              >
                <el-input
                  v-model="storeForm.userPhone"
                  clearable
                  maxlength="11"
                  placeholder="电话号码"
                  @input="storeForm.userPhone = storeForm.userPhone.replace(/[^\d]/g, '')"
                />
              </el-form-item>

              <el-form-item label="允许负库存" class="form_switch_item">
                <div style="display: flex; align-items: center; gap: 5px; height: 20px">
                  <el-switch v-model="storeForm.canNegativeStock" />
                  <span v-if="storeForm.canNegativeStock">允许</span>
                  <span v-else>不允许</span>
                </div>
              </el-form-item>
              <el-form-item label="状态" class="form_switch_item">
                <div style="display: flex; align-items: center; gap: 5px; height: 20px">
                  <el-switch v-model="storeForm.status" />
                  <span v-if="storeForm.status">启用</span>
                  <span v-else>禁用</span>
                </div>
              </el-form-item>
              <el-form-item
                prop="enableStorePosition"
                v-if="storeForm.outStoreExample === 0"
                class="form_switch_item"
              >
                <template #label>
                  <span
                    >仓位
                    <el-tooltip
                      :content="
                        storeForm.id
                          ? '创建后不可更改'
                          : '创建后不可更改,开启仓位后，商品出入库都要选择仓位'
                      "
                      placement="top"
                    >
                      <el-icon>
                        <QuestionFilled />
                      </el-icon>
                    </el-tooltip>
                  </span>
                </template>
                <div style="display: flex; align-items: center; height: 20px">
                  <el-switch
                    v-model="storeForm.enableStorePosition"
                    @change="enableStorePositionValue"
                    :disabled="storeForm.id && storeForm.id != null"
                  />
                  <HLink
                    v-if="storeForm.enableStorePosition"
                    style="margin-left: 12px"
                    @click="onAddStore"
                    >+添加仓位</HLink
                  >
                </div>
              </el-form-item>
              <template v-if="storeForm.enableStorePosition">
                <div
                  style="
                    display: flex;
                    flex-direction: column;
                    gap: 12px;
                    max-height: 200px;
                    overflow-y: auto;
                  "
                  ref="storeListRef"
                >
                  <template v-for="(i, index) in storeForm.storePositionVos" :key="index">
                    <el-form-item
                      :label="index == 0 ? '仓位名称' : ''"
                      :prop="`storePositionVos[${index}][name]`"
                      :rules="[
                        { required: true, message: '请输入仓位名称', trigger: ['blur', 'change'] },
                      ]"
                      :class="{
                        form_input_item: true,
                        error_form_item: !formValidateResult[`storePositionVos[${index}][name]`],
                      }"
                    >
                      <div style="display: flex; align-items: center; width: 100%">
                        <el-input
                          v-model="i.name"
                          clearable
                          placeholder="请输入仓位名称"
                          maxlength="30"
                          style="flex: 1"
                        />
                        <el-tooltip v-if="storeForm.id" content="仓位,是否禁用" placement="top">
                          <el-switch style="margin-left: 12px" v-model="i.status" />
                        </el-tooltip>
                        <el-tooltip content="删除仓位" placement="right">
                          <el-icon
                            size="20"
                            color="#f56c6c"
                            style="margin-left: 12px"
                            @click="deleteItem(i, index)"
                          >
                            <Remove />
                          </el-icon>
                        </el-tooltip>
                      </div>
                    </el-form-item>
                  </template>
                </div>
              </template>
            </el-form>
          </div>

          <template #footerLeft>
            <HPlainBgButton is-modal v-if="storeForm.id" type="error" @click="deleteClick"
              >删除</HPlainBgButton
            >
          </template>
          <template #footerRight>
            <HButton type="primary" is-modal @click="onSave">保存</HButton>
            <HButton is-modal @click="onClose">取消</HButton>
          </template>
        </HModal>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import Pagination from '@/components/Pagination/index.vue'
  import {
    Search,
    RefreshRight,
    Delete,
    FolderRemove,
    FolderChecked,
    Warning,
    CircleCheck,
    QuestionFilled,
    Remove,
    ArrowDown,
  } from '@element-plus/icons-vue'
  import SingleAddress from '@/components/address/singleAddress.vue'
  import useStore from './useStore'
  import HPlainButton from '@/components/common/button/HPlainButton.vue'
  import HButton from '@/components/common/button/HButton.vue'
  import HPlainBgButton from '@/components/common/button/HPlainBgButton.vue'
  import HLink from '@/components/common/link/HLink.vue'
  import HStatus from '@/components/common/status/HStatus.vue'
  import HModal from '@/components/common/Modal/HModal.vue'
  import useFormValidateService from '@/services/common/formValidate/useFormValidate'
  import pageComponentName from '@/config/page-component-name'

  defineOptions({
    name: pageComponentName.storage.storageList,
  })

  const {
    handleChange,
    getListStoreRows,
    closeClick,
    changeAll,
    storeListRef,
    clearVlaue,
    getDetailStoreItem,
    submitForm,
    addressValChange,
    enableStorePositionValue,
    ruleFormRef,
    addDialog,
    addrs,
    addrsDom,
    rulesStore,
    showAdd,
    deleteClick,
    storeForm,
    loading,
    total,
    goDetailPage,
    InWidthOutStoreQty,
    addItem,
    deleteItem,
    ids,
    pagination,
    tableDataList,
    storeListSearch,
    outStoreRelation,
    onRelationChange,
    onRelationREmoetMethod,
  } = useStore()

  const { handleFormValidate, formValidateResult, resetFormValidateResult, addFormItemName } =
    useFormValidateService([
      'address',
      'name',
      'outStoreExample',
      'userName',
      'userPhone',
      'province',
      'relationId',
      'storePositionVos[0][name]',
    ])

  /**
   * 关闭事件
   */
  const onClose = () => {
    resetFormValidateResult()
    closeClick()
  }

  /**
   * 保存事件
   */
  const onSave = () => {
    resetFormValidateResult()
    submitForm()
  }

  /**
   * 添加仓位事件
   */
  const onAddStore = () => {
    addItem()
    addFormItemName(`storePositionVos[${storeForm.value.storePositionVos.length - 1}][name]`)
  }
</script>

<style scoped lang="scss">
  @import './index';
</style>
